// pages/editCard/editCard.js 
const recorderManager = wx.getRecorderManager()   //创建录音对象
const innerAudioContext = wx.createInnerAudioContext();  //创建音频对象
const app = getApp()
var recorderNum;
Page({
  /**
   * 页面的初始数据
   */ 
  data: {
    avatar:'',
    nickName:'',
    voice:'1',
    hasmusic:false,
    changelogo: false,
    hasluyin:false,
    greet:'',
    scend:60,
  },
  greetinput: function (e) {
    this.setData({
      greet: e.detail.value
    })
    var greet = wx.getStorageSync('greet');
    if(greet){
      greet.content = e.detail.value;
      wx.setStorageSync('greet', greet)
    }
  },
  nameinput: function (e) {
    this.setData({
      nickName: e.detail.value
    })
  },
  makecard: function () {
    var that = this
    var data = wx.getStorageSync('requestdata');
    data.hbtype = 1
    wx.request({
      url: app.siteinfo.rootpath + 'createhb',
      data: data,
      success: function (res) {
        if (res.data.code == 200) {
          wx.removeStorageSync('music')
          wx.removeStorageSync('greet')
          wx.removeStorageSync('requestdata')
          wx.redirectTo({
            url: '/pages/preview/preview?id=' + res.data.id,
          })

        } else {
          wx.showToast({
            title: '贺卡生成失败',
            icon: "none"
          })
        }
      }
    })
    // console.log(data)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this
    var id = options.id
    that.setData({
      avatar: app.siteinfo.userinfo.logo,
      nickName: app.siteinfo.userinfo.wechat_name,
      hid: id
    })
    
    /* ----------------------监听录音事件---------------------- */
    // 录音停止的回调处理
    recorderManager.onStop(function (res) {
      console.log('录音结束')
      
      clearInterval(recorderNum)
      // 停止录音之后，把录取到的音频放在res.tempFilePath
      that.setData({
        audiopath: res.tempFilePath
      })
      // 保存录音文件
      wx.saveFile({
        tempFilePath: res.tempFilePath,
        success: function (res) {
          //持久路径 
          //本地文件存储的大小限制为 100M 
          var savedFilePath = res.savedFilePath
          that.setData({
            audiopath: savedFilePath
          })
          console.log("savedFilePath: " + savedFilePath)
          innerAudioContext.src = savedFilePath;  // 设置音频地址
        }
      })
    });

    // 播放音频至结束的回调
    innerAudioContext.onEnded((res) => {
      console.log('录音播放结束')
      this.setData({
        voice: '3'
      })
    })
    // 播放音频失败的回调
    innerAudioContext.onError((res) => {
      console.log('录音失败')
      this.setData({
        voice: '3'
      })
    })
  },
  /* ----------------------开始语音录制---------------------- */
  openRecorderHandle: function () {
    let that = this
    let { voice, scend } = that.data
    innerAudioContext.stop() // 关闭当前播放音频
    recorderManager.start({  // 开始录音
      format: 'mp3'  // 如果录制acc类型音频则改成aac
    });
    that.setData({
      voice: '2',
      hasluyin:true,
      scend:60
    })
    setTimeout(function () {
      recorderManager.stop()// 结束录音
      that.setData({
        voice: '3'
      })
    }, 60000)
     recorderNum = setInterval(function () {
      let scendNew = that.data.scend
      
      if (scendNew == 0){
        clearInterval(recorderNum)
      }else{
        that.setData({
          scend: scendNew - 1
        })
      }
      
    }, 1000)
  },
  /* ----------------------结束语音录制---------------------- */
  stopRecorderHandle: function () {
    recorderManager.stop()
    clearInterval(recorderNum)
    this.setData({
      voice: '3'
    })
  },
  // 
  /* ----------------------播放录音---------------------- */
  playVoiceHandle: function () {
    innerAudioContext.play()
    this.setData({
      voice: '4'
    })
  },
  /* ----------------------关闭当前播放音频---------------------- */
  stopVoiceHandle: function(){
    innerAudioContext.stop()  
    this.setData({
      voice: '3'
    })
  },
  /* ----------------------删除当前录音---------------------- */
  delVoiceHandle: function () {
    this.setData({
      voice: '1',
      hasluyin:false,
      scend:60
    })
  },
  /* ----------------------更改头像---------------------- */
  avatarHandle: function () {
    let that = this
    let avatar = that.data.avatar
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        // tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFilePaths
        that.setData({
          avatar:tempFilePaths,
          changelogo:true,
        })
      }
    })
  },
  /* ----------------------选择背景音乐---------------------- */
  changeMusic: function () {
    wx.navigateTo({
      url: '/pages/music/music',
    })
  },
  /* ----------------------选择祝福语---------------------- */
  greetingHandle: function () {
    wx.navigateTo({
      url: '/pages/greeting/greeting',
    })
  },
  /* ----------------------保存---------------------- */
  saveHandle: function () {
    var that = this;
    // console.log(that.data.changelogo);
    // console.log(that.data.hasluyin);
    var iscom = app.siteinfo.userinfo.iscompany
    var avatar = that.data.avatar;
    var hid = that.data.hid;
    var hasluyin = that.data.hasluyin;
    var changelogo = that.data.changelogo;
    var name = that.data.nickName;
    var greet = that.data.greet;

    var music = wx.getStorageSync('music');
    var chosegreet = wx.getStorageSync('greet');
    if (music){
      var musicpath = music.content
      var musicid = music.id
    }else{
      wx.showToast({
        title: '请选择背景音乐',
        icon: 'none'
      })
      return;
    }
    if (chosegreet) {
      var greetid = chosegreet.id
    } else {
      var greetid = 0
    }
    
    if(name.length<1){
      wx.showToast({
        title: '请填写姓名',
        icon:'none'
      })
      return;
    }
    if (greet.length < 1) {
      wx.showToast({
        title: '请填写祝福语',
        icon: 'none'
      })
      return;
    }

    if(changelogo){
      wx.showLoading({
        title: '头像上传中',
      })
      wx.uploadFile({
        url: app.siteinfo.rootpath +'thumbupload',
        filePath: that.data.avatar[0],
        name: 'file',
        header: {
          'content-type': 'multipart/form-data'
        },
        success:function(res){
          wx.hideLoading()
          if(res.data){
            var avatar = res.data
            if(hasluyin){
              wx.showLoading({
                title: '上传录音中',
              })
              wx.uploadFile({
                url: app.siteinfo.rootpath + 'thumbupload',
                filePath: that.data.audiopath,
                name: 'file',
                header: {
                  'content-type': 'multipart/form-data'
                },
                success: function (res) {
                  wx.hideLoading()
                  if (res.data) {
                    var audiopath = res.data
                    var requestdata = {
                        id: app.siteinfo.userinfo.id,
                        hid: hid,
                        logo: avatar,
                        name: name,
                        musicpath: musicpath,
                        musicid: musicid,
                        greet: greet,
                        greetid: greetid,
                        audiopath: audiopath
                      }
                    wx.setStorageSync('requestdata', requestdata)
                    // if(iscom == 1){
                    //   wx.navigateTo({
                    //     url: '/pages/packet3/packet3',
                    //   })
                    // }else{
                    //   wx.navigateTo({
                    //     url: '/pages/packet/packet',
                    //   })
                    // }
                    that.makecard()
                   
                  } else {
                    wx.showToast({
                      title: '录音上传失败',
                      icon: 'none'
                    })
                  }
                }, fail: function () {
                  wx.showToast({
                    title: '头像上传失败',
                    icon: 'none'
                  })
                }
              })
            }else{
              
              var requestdata= {
                  id: app.siteinfo.userinfo.id,
                  hid: hid,
                  logo: avatar,
                  name: name,
                  musicpath: musicpath,
                  musicid: musicid,
                  greet: greet,
                  greetid: greetid,
                }
              wx.setStorageSync('requestdata', requestdata)
              // if (iscom == 1) {
              //   wx.navigateTo({
              //     url: '/pages/packet3/packet3',
              //   })
              // } else {
              //   wx.navigateTo({
              //     url: '/pages/packet/packet',
              //   })
              // }
              that.makecard()
            }
          }else{
            wx.showToast({
              title: '头像上传失败',
              icon: 'none'
            })
          }
        },fail:function(){
          wx.showToast({
            title: '头像上传失败',
            icon:'none'
          })
        }
      })
    }else if(hasluyin){
      wx.showLoading({
        title: '上传录音中',
      })
      console.log(that.data.audiopath)
      wx.uploadFile({
        url: app.siteinfo.rootpath + 'thumbupload',
        filePath: that.data.audiopath,
        name: 'file',
        header: {
          'content-type': 'multipart/form-data'
        },
        success: function (res) {
          wx.hideLoading()
          if (res.data) {
            var audiopath = res.data
            var requestdata = {
              id: app.siteinfo.userinfo.id,
              hid: hid,
              logo: avatar,
              name: name,
              musicpath: musicpath,
              musicid: musicid,
              greet: greet,
              greetid: greetid,
              audiopath: audiopath
            }
            wx.setStorageSync('requestdata', requestdata)
            // if (iscom == 1) {
            //   wx.navigateTo({
            //     url: '/pages/packet3/packet3',
            //   })
            // } else {
            //   wx.navigateTo({
            //     url: '/pages/packet/packet',
            //   })
            // }
            that.makecard()
          } else {
            wx.showToast({
              title: '录音上传失败',
              icon: 'none'
            })
          }
        }, fail: function () {
          wx.showToast({
            title: '录音上传失败',
            icon: 'none'
          })
        }
      })
    }else{
      var requestdata = {
        id: app.siteinfo.userinfo.id,
        hid:hid,
        logo: avatar,
        name: name,
        musicpath: musicpath,
        musicid: musicid,
        greet: greet,
        greetid: greetid,
      }
      wx.setStorageSync('requestdata', requestdata)
      // if (iscom == 1) {
      //   wx.navigateTo({
      //     url: '/pages/packet3/packet3',
      //   })
      // } else {
      //   wx.navigateTo({
      //     url: '/pages/packet/packet',
      //   })
      // }
      that.makecard()
    }
    
    
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    var music = wx.getStorageSync('music')
    var greet = wx.getStorageSync('greet')
    if(music){
      that.setData({
        musicname:music.title,
        hasmusic:true
      })
    }
    if (greet) {
      // var content = greet.content.replace(/@#$/g, " ");
      var content = greet.content.split("@#$");
      content = content.join(',');
      that.setData({
        greet: content,
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    innerAudioContext.stop() // 关闭当前播放音频
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // }
})